package space.yangmin.baidu.downloader.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import space.yangmin.baidu.downloader.bo.FileInfoBO;
import space.yangmin.baidu.downloader.controller.base.BaseController;
import space.yangmin.baidu.downloader.dto.FileInfoDTO;
import space.yangmin.baidu.downloader.dto.ListFileDTO;
import space.yangmin.baidu.downloader.service.FileService;
import space.yangmin.baidu.downloader.util.R;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
@AllArgsConstructor
@Slf4j
public class FileController extends BaseController {

    private final FileService fileService;

    @PostMapping
    public R listFile(@RequestBody ListFileDTO dto){
        return R.ok(this.fileService.listFile(dto));
    }

    @GetMapping("/fileInfo")
    public Object fileInfo(FileInfoDTO dto){
        return this.fileService.getFileInfo(dto);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String fsid){
        FileInfoDTO fileInfoDTO = FileInfoDTO.builder()
                .fsids(new Long[]{Long.parseLong(fsid)})
                .dlink(1)
                .build();
        List<FileInfoBO> fileInfoBOS = this.fileService.getFileInfo(fileInfoDTO);
        Assert.isTrue(CollUtil.isNotEmpty(fileInfoBOS),"文件不存在");
        File workDir = FileUtil.mkdir("downloader_" + DateUtil.format(new Date(), "yyyyMMdd_HHmmss"));
        log.info("工作目录：{}", workDir.getAbsolutePath());

        FileInfoBO fileInfoBO = fileInfoBOS.get(0);
        String filePath = this.fileService.downloadFile(fileInfoBO, workDir.getAbsolutePath());
        if(StrUtil.isNotBlank(filePath)){
            try{
                FileInputStream fileInputStream = new FileInputStream(filePath);
                InputStream fis = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();

                response.setCharacterEncoding("UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileInfoBO.getFilename(), "UTF-8"));
                // 告知浏览器文件的大小
                response.addHeader("Content-Length", "" + fileInfoBO.getSize());
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                outputStream.write(buffer);
                outputStream.flush();
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                FileUtil.del(workDir);
            }
        }else{
            try {
                response.getWriter().write("下载失败");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
